package com.im.partchat.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.im.partchat.R;
import com.im.partchat.adapter.DocDownAdapter;
import com.im.partchat.adapter.base.XRecyclerViewAdapter;
import com.im.partchat.base.BaseActivity;
import com.im.partchat.bean.more.DocBean;
import com.im.partchat.http.service.DownLoadService;
import com.im.partchat.utils.FileUtils;
import com.im.partchat.utils.SPUtils;
import com.im.partchat.utils.rxlifecycle.compact.RxLifecycleCompact;

import org.reactivestreams.Publisher;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;

public class DocDownloadActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private List<DocBean> docBeanList = new ArrayList<>();

    private DocDownAdapter docDownAdapter;

    @Override
    public void onLoadDataSuccess(Object o, String flag) {

    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_doc_download;
    }

    @Override
    protected void initData() {

        docBeanList.add(new DocBean("我是测试文档1", "http://7xl7dy.com1.z0.glb.clouddn.com/%E8%BE%85%E8%AD%A6%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F.docx"));
        docBeanList.add(new DocBean("我是测试文档2", "http://7xl7dy.com1.z0.glb.clouddn.com/%E8%BE%85%E8%AD%A6%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F.docx"));
        docBeanList.add(new DocBean("我是测试文档3", "http://7xl7dy.com1.z0.glb.clouddn.com/%E8%BE%85%E8%AD%A6%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F.docx"));
        docBeanList.add(new DocBean("我是测试文档4", "http://7xl7dy.com1.z0.glb.clouddn.com/%E8%BE%85%E8%AD%A6%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F.docx"));
        docBeanList.add(new DocBean("我是测试文档5", "http://7xl7dy.com1.z0.glb.clouddn.com/%E8%BE%85%E8%AD%A6%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F.docx"));

        Flowable.just(docBeanList)
                .flatMap(new Function<List<DocBean>, Publisher<DocBean>>() {
                    @Override
                    public Publisher<DocBean> apply(List<DocBean> docBeen) throws Exception {
                        return Flowable.fromIterable(docBeen);
                    }
                })
                .map(new Function<DocBean, DocBean>() {
                    @Override
                    public DocBean apply(DocBean docBean) throws Exception {
                        String url = SPUtils.getString(docBean.getUrl(), "");

                        String fileExt = FileUtils.getFileExt(docBean.getUrl());
                        String filePath = Environment.getExternalStorageDirectory() + File.separator + docBean.getTitle() + "." + fileExt;
                        if (TextUtils.isEmpty(url)) {
                            docBean.setStstus(0);
                        } else {
                            if (FileUtils.isFileExist(filePath)) {
                                docBean.setStstus(1);
                            } else {
                                docBean.setStstus(0);
                            }
                        }
                        return docBean;
                    }
                }).toList()
                .subscribe(new SingleObserver<List<DocBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(List<DocBean> value) {
                        docBeanList = value;
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        docDownAdapter = new DocDownAdapter(this, recyclerView, docBeanList);
        recyclerView.setAdapter(docDownAdapter);
        docDownAdapter.setOnItemClickListener(new XRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                DocBean docBean = docBeanList.get(position);
                if (docBean.getStstus() == -1) {
                    return;
                }
                String fileExt = FileUtils.getFileExt(docBean.getUrl());
                String filePath = Environment.getExternalStorageDirectory() + File.separator + docBean.getTitle() + "." + fileExt;
                if (docBean.getStstus() == 1 && FileUtils.isFileExist(filePath)) {
                    try {
                        Intent intent = FileUtils.openFile(new File(filePath));
                        startActivity(intent);
                    } catch (Exception e) {
                        showToast("未发现合适的程序来打开此文件，请下载wps后重试");
                        e.printStackTrace();
                    }

                } else {
                    downLoadFile(docBean.getTitle(), docBean.getUrl(), position);

                }
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url url
     */
    public void downLoadFile(String fileName, final String url, final int position) {

        if (TextUtils.isEmpty(url)) {
            showToast("文件路径有误");
            return;
        }
        String fileExt = FileUtils.getFileExt(url);
        if (TextUtils.isEmpty(fileName)) {
            fileName = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        }
        final String filePath = Environment.getExternalStorageDirectory() + File.separator + fileName + "." + fileExt;
        final String finalFileName = fileName;
        DownLoadService.downLoadFile(url)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody body) throws Exception {
                        InputStream in = null;
                        FileOutputStream out = null;
                        try {

                            in = null;
                            out = null;
                            in = body.byteStream();
                            out = new FileOutputStream(filePath);
                            int c;

                            while ((c = in.read()) != -1) {
                                out.write(c);
                            }
                        } catch (IOException e) {

                        } finally {
                            if (in != null) {
                                in.close();
                            }
                            if (out != null) {
                                out.close();
                            }
                        }
                        return url;
                    }
                })
                .compose(RxLifecycleCompact.bind(this).<String>withObservable())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        docBeanList.get(position).setStstus(-1);
                        docDownAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onNext(String value) {
                        docBeanList.get(position).setStstus(1);
                        docDownAdapter.notifyDataSetChanged();
                        showToast("下载完成，" + finalFileName + "存放路径," + filePath);
                        SPUtils.saveString(url, url);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showToast("下载失败,请确定文件路径是否正确");
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }


}
